<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="座位编号" prop="number">
        <el-input v-model="queryParams.number" placeholder="请输入座位编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="isMaintain">
        <el-select v-model="queryParams.isMaintain" placeholder="座位状态" clearable>
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
            :value="dict.value === '0' ? false : true" />
        </el-select>
      </el-form-item>
      <el-form-item label="自习室" prop="roomId">
        <el-select v-model="queryParams.roomId" placeholder="请选择自习室" clearable filterable @focus="loadRoomOptions">
          <el-option v-for="item in roomOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:seat:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:seat:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:seat:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="seatList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="80">
        <template slot-scope="scope">
          <span>{{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="座位ID" align="center" prop="id" v-if="false" />
      <!-- 隐藏实际ID列 -->
      <el-table-column label="所属自习室" align="center">
        <template slot-scope="scope">
          <span v-if="roomOptions.length === 0 && !loading">
            <i class="el-icon-loading"></i> 加载中...
          </span>
          <span v-else>
            {{ getRoomName(scope.row.roomId) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="座位编号" align="center" prop="number" />
      <el-table-column label="所在行" align="center" prop="SRow" />
      <el-table-column label="所在列" align="center" prop="SCol" />
      <el-table-column label="状态" align="center" prop="isMaintain">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.isMaintain ? '1' : '0'" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:seat:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:seat:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改座位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="座位编号" prop="number">
          <el-input v-model="form.number" placeholder="请输入座位编号" />
        </el-form-item>
        <el-form-item label="所在行" prop="SRow">
          <el-input-number v-model="form.SRow" :min="1" controls-position="right" />
        </el-form-item>
        <el-form-item label="所在列" prop="SCol">
          <el-input-number v-model="form.SCol" :min="1" controls-position="right" />
        </el-form-item>
        <el-form-item label="所属自习室" prop="roomId">
          <el-select v-model="form.roomId" placeholder="请选择自习室" clearable filterable @focus="loadRoomOptions">
            <el-option v-for="item in roomOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="座位状态" prop="isMaintain">
          <el-radio-group v-model="form.isMaintain">
            <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value"
              :label="dict.value === '0' ? false : true">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getSeatListAPI,
  getSeatInfoAPI,
  addSeatAPI,
  updateSeatAPI,
  deleteSeatAPI,
} from "@/api/resource/seat";
import { getRoomListAPI } from "@/api/resource/room";

export default {
  name: "Seat",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      //自习室选项
      roomOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 座位表格数据
      seatList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        number: undefined,
        isMaintain: undefined,
        roomId: undefined,
      },
      // 表单参数
      form: {
        SRow: 1,
        SCol: 1,
        isMaintain: false,
      },
      // 表单校验
      rules: {
        number: [
          { required: true, message: "座位编号不能为空", trigger: "blur" },
        ],
        roomId: [{ required: true, message: "请选择自习室", trigger: "change" }],
        SRow: [{ required: true, message: "所在行不能为空", trigger: "blur" }],
        SCol: [{ required: true, message: "所在列不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
    this.loadRoomOptions(); // 加载自习室选项
  },
  methods: {

    /** 根据roomId获取自习室名称 */
    getRoomName(roomId) {
      if (!roomId) return '-';
      if (this.roomOptions.length === 0) return '加载中...';
      const room = this.roomOptions.find(item => item.id == roomId);
      return room ? room.name : '未知自习室';
    },
    /** 加载自习室选项 */
    async loadRoomOptions() {
      if (this.roomOptions.length > 0) return; // 如果已加载则不再重复加载

      try {
        this.loading = true;
        const response = await getRoomListAPI({ pageNum: 1, pageSize: 1000 });
        if (response.code === 200) {
          this.roomOptions = response.rows;
        } else {
          this.$message.error('加载自习室列表失败: ' + (response.msg || '未知错误'));
        }
      } catch (error) {
        this.$message.error('加载自习室列表出错: ' + error.message);
      } finally {
        this.loading = false;
      }
    },
    /** 查询座位列表 */
    getList() {
      this.loading = true;
      getSeatListAPI(this.queryParams).then((response) => {
        this.seatList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        number: undefined,
        SRow: 1,
        SCol: 1,
        isMaintain: false,
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加座位";
      this.loadRoomOptions();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getSeatInfoAPI(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改座位";
        this.loadRoomOptions();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateSeatAPI(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSeatAPI(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 删除按钮点击事件
    handleDelete(row) {
      const ids = row.id ? [row.id] : this.ids;
      this.$modal
        .confirm("确认删除选中的数据？")
        .then(() => {
          deleteSeatAPI(ids)
            .then((response) => {
              this.$modal.msgSuccess("删除成功");
              this.getList(); // 刷新列表
            })
            .catch((error) => {
              this.$modal.msgError("删除失败: " + (error.message || error));
            });
        })
        .catch(() => { });
    },
  },
};
</script>
